package com.forsir.android.mhfinance;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;

import com.forsir.android.mhfinance.storeObjects.Account;
import com.forsir.android.mhfinance.storeObjects.AccountsList;
import com.forsir.android.mhfinance.storeObjects.Category;
import com.forsir.android.mhfinance.storeObjects.CategoryList;
import com.forsir.android.mhfinance.storeObjects.Repeating;
import com.forsir.android.mhfinance.storeObjects.RepeatingList;
import com.forsir.android.mhfinance.storeObjects.Subcategory;

public class MHFinance extends SelectCategory {
	private static final String TAG = "MHFinance";

	private Button accountButton;
	private Button transferButton;
	private LinearLayout transferLayout;
	private TextView accountText;
	private TextView categoryText;

	private Account actualAccount = null;

	private static final int SET_AMOUNT_ACTIVITY = 100;
	private static final int SELECT_ACCOUNT_ACTIVITY = 101;
	private static final int PREFERENCES_ACTIVITY = 102;
	private static final int REPORT_LIST_ACTIVITY = 103;
	private static final int REPORT_SUMMARY_ACTIVITY = 104;

	private static final String SAVE_ACTUAL_ACCOUNT_ID = "actual_account_id";

	private static int lastAccountId = -1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

		super.onSuperCreate(savedInstanceState);
		setContentView(R.layout.main);

		if (CategoryList.isEmpty()) {
			CategoryList.loadAll(mDbHelper);
		}
		if (AccountsList.isEmpty()) {
			AccountsList.loadAll(mDbHelper);
		}
		if (RepeatingList.isEmpty()) {
			RepeatingList.loadAll(mDbHelper);
		}
		Repeating.generateAllRepeatedPayments(mDbHelper);

		categoriesListView = (ExpandableListView) findViewById(R.id.main_category_view);
		categoriesListView.setOnItemLongClickListener(itemLongClickListener);
		categoriesListView.setOnChildClickListener(onCategoryChildClickListener);
		categoriesListView.setOnGroupClickListener(groupClickListener);
		registerForContextMenu(categoriesListView);

		accountButton = (Button) findViewById(R.id.main_account_select);
		accountButton.setOnClickListener(clickAccountListener);

		transferLayout = (LinearLayout) findViewById(R.id.main_transfer_layout);
		transferButton = (Button) findViewById(R.id.main_transfer);
		transferButton.setOnClickListener(clickTransferListener);

		accountText = (TextView) findViewById(R.id.main_account_text);
		categoryText = (TextView) findViewById(R.id.main_category_text);

		if (savedInstanceState != null) {
			actualAccount = AccountsList.getAccountByIdOrFirst(savedInstanceState.getLong(SAVE_ACTUAL_ACCOUNT_ID, -1));
		}

		if (actualAccount == null) {
			actualAccount = AccountsList.getLastAccount(lastAccountId, mDbHelper);
		}

		setAccountName();
		fillCategoryData();
		checkTexts();
		checkTransferButton();
	}

	@Override
	public void checkTexts() {
		if (AccountsList.getAccounts().size() == 0) {
			accountText.setText(R.string.create_new_account);
			accountText.setTextColor(getResources().getColor(R.color.hint));
		} else {
			accountText.setText(R.string.select_account);
			accountText.setTextColor(Color.WHITE);
		}
		if (CategoryList.getCategories().size() == 0) {
			categoryText.setText(R.string.create_new_category);
			categoryText.setTextColor(getResources().getColor(R.color.hint));
		} else {
			if (!CategoryList.hasSubcategories()) {
				categoryText.setTextColor(getResources().getColor(R.color.hint));
				categoryText.setText(R.string.create_new_subcategory);
			} else {
				categoryText.setTextColor(Color.WHITE);
				categoryText.setText(R.string.select_category);
			}
		}
	}

	public void checkTransferButton() {
		if (mPreferenceSettings.getBoolean(getString(R.string.key_show_transfer_button), false)) {
			transferLayout.setVisibility(View.VISIBLE);
		} else {
			transferLayout.setVisibility(View.GONE);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		final MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		final Intent intent;
		switch (item.getItemId()) {
			case R.id.menu_view_category:
				intent = new Intent(MHFinance.this, Report.class);
				intent.putExtra(Report.REQUEST_REPORT_TYPE, Report.TYPE_SUBCATEGORY);
				startActivityForResult(intent, REPORT_LIST_ACTIVITY);
				return true;
			case R.id.menu_view_list:
				intent = new Intent(MHFinance.this, Report.class);
				intent.putExtra(Report.REQUEST_REPORT_TYPE, Report.TYPE_LIST);
				startActivityForResult(intent, REPORT_SUMMARY_ACTIVITY);
				return true;
			case R.id.menu_report:
				intent = new Intent(MHFinance.this, Report.class);
				final String defaultReport = mPreferenceSettings.getString(getString(R.string.key_default_report), String.valueOf(Report.TYPE_SUMMARY));
				intent.putExtra(Report.REQUEST_REPORT_TYPE, Integer.parseInt(defaultReport));
				startActivityForResult(intent, REPORT_SUMMARY_ACTIVITY);
				return true;
			case R.id.menu_view_summary:
				intent = new Intent(MHFinance.this, Report.class);
				intent.putExtra(Report.REQUEST_REPORT_TYPE, Report.TYPE_SUMMARY);
				startActivityForResult(intent, REPORT_SUMMARY_ACTIVITY);
				return true;
			case R.id.menu_preferences:
				intent = new Intent(MHFinance.this, SetPreferences.class);
				startActivityForResult(intent, PREFERENCES_ACTIVITY);
				return true;
		}
		return false;
	}

	private void setAccountName() {
		if (actualAccount == null) {
			accountButton.setText(R.string.menu_account_new);
		} else {
			accountButton.setText(actualAccount.getName());
		}
	}

	private final OnClickListener clickAccountListener = new OnClickListener() {
		public void onClick(View v) {
			final Intent i = new Intent(MHFinance.this, SelectAccount.class);
			startActivityForResult(i, SELECT_ACCOUNT_ACTIVITY);
		}
	};

	private final OnClickListener clickTransferListener = new OnClickListener() {
		public void onClick(View v) {
			showSetAmountActivity(-1, true);
		}
	};

	private final OnChildClickListener onCategoryChildClickListener = new OnChildClickListener() {
		public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
			final Subcategory subcategory = CategoryList.getSubcategory(groupPosition, childPosition);
			if (subcategory != null) {
				showSetAmountActivity(subcategory.getId(), false);
			} else {
				final Category category = CategoryList.getCategory(groupPosition);
				parentItemId = category.getId();
				addNewSubCategory();
			}
			return false;
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
			case SELECT_ACCOUNT_ACTIVITY:
				if (resultCode == RESULT_OK) {
					final int index = data.getIntExtra(SelectAccount.RETURN_ACCOUNT_POSITION, -1);
					if (index >= 0) {
						actualAccount = AccountsList.getAccount(index);
					}
				} else {
					if (actualAccount != null) {
						actualAccount = AccountsList.getAccountByIdOrFirst(actualAccount.getId());
					}
				}
				setAccountName();
				checkTexts();
				break;
			case PREFERENCES_ACTIVITY:
				mAddNewType = mPreferenceSettings.getString(getString(R.string.key_new_item), getResources().getStringArray(R.array.preferences_new)[0]);
				fillCategoryData();
				checkTransferButton();
				break;
			case SET_AMOUNT_ACTIVITY:
				if (resultCode == RESULT_OK) {
					final boolean showReport = data.getBooleanExtra(SetAmount.RETURN_SHOW_REPORT, false);
					if (showReport) {
						final Intent intent = new Intent(MHFinance.this, Report.class);
						final String defaultReport = mPreferenceSettings.getString(getString(R.string.key_default_report), String.valueOf(Report.TYPE_SUMMARY));
						intent.putExtra(Report.REQUEST_REPORT_TYPE, Integer.parseInt(defaultReport));
						startActivityForResult(intent, REPORT_SUMMARY_ACTIVITY);
					}
				}
				break;
		}
	}

	private void showSetAmountActivity(long categoryId, boolean transfer) {
		final Intent i = new Intent(this, SetAmount.class);
		if (actualAccount == null) {
			Toast.makeText(this, R.string.account_must_be_select, Toast.LENGTH_LONG).show();
			return;
		}

		Log.d(TAG, "Set start SetAmount account_id = " + actualAccount.getId() + ", category_id = " + categoryId + ".");
		i.putExtra(SetAmount.REQUEST_ACCOUNT_ID, actualAccount.getId());
		i.putExtra(SetAmount.REQUEST_CATEGORY_ID, categoryId);
		i.putExtra(SetAmount.REQUEST_TRANSFER, transfer);
		startActivityForResult(i, SET_AMOUNT_ACTIVITY);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (actualAccount != null) {
			outState.putLong(SAVE_ACTUAL_ACCOUNT_ID, actualAccount.getId());
		}
	}
}
